package com.markedquilt.comment.service.impl;

import com.markedquilt.comment.coomon.BussinessException;
import com.markedquilt.comment.coomon.EmBussinessError;
import com.markedquilt.comment.dao.UserModelMapper;
import com.markedquilt.comment.model.UserModel;
import com.markedquilt.comment.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.DuplicateFormatFlagsException;

/**
 * @author ZhangKe
 * @Description
 * @date 2020/4/18 16:48.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserModelMapper userModelMapper;

    @Override
    public UserModel getUser(Integer id) {
        return userModelMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public UserModel register(UserModel userModel) throws BussinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        userModel.setPassword(encodeByMd5(userModel.getPassword()));
        userModel.setCreatedAt(new Date());
        userModel.setUpdatedAt(new Date());

        try{
            userModelMapper.insertSelective(userModel);
        }catch (DuplicateKeyException ex){
            /** 主键或者唯一键冲突  */
            throw new BussinessException(EmBussinessError.REGISTER_DUP_FAIL);
        }
        return getUser(userModel.getId());
    }

    @Override
    public UserModel login(String telphone, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException, BussinessException {
        UserModel userModel=userModelMapper.selectByTelphoneAndPassword(telphone, encodeByMd5(password));
        if (userModel==null){
            throw new BussinessException(EmBussinessError.LOGIN_FAIL);
        }
        return userModel;
    }

    @Override
    public Integer countAllUser() {
        return userModelMapper.countAllUser();
    }

    private String encodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest=MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder=new BASE64Encoder();
        return base64Encoder.encode(messageDigest.digest(str.getBytes("utf-8")));
    }
}
